import 'package:flutter/material.dart';
import 'package:lib_uikit/widgets/gt_dialog_loading.dart';
import 'package:lib_core/lib_core.dart';

/// Dialog辅助类,缓存Dialog的context,方便在其他地方关闭Dialog
class GTDialogHelper {

  static Map<Widget, BuildContext> map = {};

  static Widget? show([BuildContext? context, Widget? dialog, bool? isTransparent]) {
    context ??= GTNavigatorProvider.currentContext;
    if (context == null) {
      return dialog;
    }

    isTransparent ??= false;
    dialog ??= const GTLoadingDialog();
    showDialog(
      context: context,
      barrierColor: isTransparent ? Colors.transparent : Colors.black54,
      builder: (BuildContext context) {
        map[dialog!] = context;
        return dialog;
      },
    );

    return dialog;
  }

  static void hideAndRelease([Widget? dialog]) {
    // 获取 context
    BuildContext? context;
    if (dialog != null) {
      context = map[dialog];
    } else {
      context = GTNavigatorProvider.currentContext;
    }
    if (context == null) {
      return;
    }

    map.remove(dialog);
    if (!context.mounted) return;
    var navigator = Navigator.of(context);
    if (navigator.canPop()) {
      navigator.pop();
    }
  }
}
